#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string>
#include <string.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "usage:./client ip port" << std::endl;
    }

    // 1. 创建套接字
    int socketId = socket(AF_INET, SOCK_DGRAM, 0);
    if (socketId < 0)
    {
        std::cout << "socket error" << std::endl;
        exit(1);
    }
    // 2. 发送消息给服务器
    struct sockaddr_in ser_addr;
    memset(&ser_addr, 0, sizeof(ser_addr));
    ser_addr.sin_family = AF_INET;
    ser_addr.sin_addr.s_addr = inet_addr(argv[1]);
    ser_addr.sin_port = htons(atoi(argv[2]));

    while (1)
    {
        std::string message;
        std::cout << ">>>Client Send<<<" << std::endl;
        getline(std::cin, message);
        sendto(socketId, message.c_str(), message.size(), 0, (struct sockaddr *)&ser_addr, sizeof(ser_addr)); // 发送给服务器

        char buffer[1024];
        socklen_t len = sizeof(ser_addr);
        ssize_t s = recvfrom(socketId, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&ser_addr, &len);
        if (s > 0)
        {
            buffer[s] = 0;

            if (!strcmp("quit", buffer))
            {
                break;
            }
            std::cout << ">>>Server Return<<<" << std::endl;
            std::cout << buffer << std::endl;
        }
    }

    return 0;
}